package cn.huapu.power.energy.util;

import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
/**
* @Author jzx
* @Description //json工具类
* @Date 8:19 2019-5-14
* @Param
* @return
**/
public class JsonUtils {
	/**
	 * 字节数组转化为输入流，格式为UTF-8
	 * @param s 目标字符串
	 * @return InputStream 从流中读取数据
	 * @throws Exception 顶级异常
	 */
	public static InputStream stringToInputStream(String s) throws Exception {
		return new ByteArrayInputStream(s.getBytes("UTF-8"));
	}
	/**
	 * 将obj转化为字节数组输入流
	 * @param obj 顶级父类
	 * @return InputStream 从流中读取数据
	 * @throws Exception 顶级异常
	 */
	public static InputStream objToInputStream(Object obj) throws Exception {
		return stringToInputStream(objToJson(obj));
	}
	/**
	 * Object转化为Json序列，输出方式为字符串
	 * @param obj 顶级父类
	 * @return String 
	 * @throws Exception 顶级异常
	 */
	public static String objToJson(Object obj) throws Exception {
		ObjectMapper mapper = new ObjectMapper();
		return mapper.writeValueAsString(obj);
	}
	/**
	 * 目标字符串拼接Json字符串
	 * @param callback 目标字符串
	 * @param obj 顶级父类
	 * @return String 目标字符串
	 * @throws Exception 顶级异常
	 */
	public static String objToJson(String callback,Object obj) throws Exception {
		ObjectMapper mapper = new ObjectMapper();
		return callback+"("+mapper.writeValueAsString(obj)+")";
	}
	/**
	 * 拼接字符串并转化为输入流
	 * @param callback 目标字符串
	 * @param obj 顶级父类
	 * @return InputStream 从流中读取数据
	 * @throws Exception 顶级异常
	 */
	public static InputStream objToInputStream(String callback,Object obj) throws Exception {
		return stringToInputStream(objToJson(callback,obj));
	}
	/**
	 * 将json字符串转换成Map集合
	 * @param json 目标字符串
	 * @return Map<String,Object> Map集合
	 * @throws Exception 顶级异常
	 */
	@SuppressWarnings("unchecked")
	public static Map<String,Object> jsonToMap(String json)throws Exception{	
		ObjectMapper mapper = new ObjectMapper(); 	
		Map<String,Object> map = mapper.readValue(json, HashMap.class);  
		return map;
	}
	/**
	 * 将json字符串转换成Object类型
	 * @param json 目标字符串
	 * @param c 类
	 * @return Object 顶级父类
	 * @throws Exception 顶级异常
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static Object jsonToObj(String json,Class c)throws Exception{	
		ObjectMapper mapper = new ObjectMapper(); 
		Object o = mapper.readValue(json,c);  
		return o;
	}
}
